package com.un.ebs.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.un.ebs.core.enums.IndustryTypeEnum;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.sys.domain.AppTenant;
import com.un.ebs.sys.domain.Ent;
import com.un.ebs.sys.domain.EntLinkman;
import com.un.ebs.sys.domain.EntPersonnel;
import com.un.ebs.sys.dto.EntAddDto;
import com.un.ebs.sys.dto.EntLinkmanDto;
import com.un.ebs.sys.dto.EntUpdateDto;
import com.un.ebs.sys.mapper.EntLinkmanMapper;
import com.un.ebs.sys.mapper.EntMapper;
import com.un.ebs.sys.mapper.EntPersonnelMapper;
import com.un.ebs.sys.service.AppTenantService;
import com.un.ebs.sys.service.DictionaryAreaService;
import com.un.ebs.sys.service.EntService;
import com.un.ebs.sys.service.PersonnelService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author liubo
 * @since 2019-09-15
 */
@Service
public class EntServiceImpl extends ServiceImpl<EntMapper, Ent> implements EntService {

    @Autowired
    private AppTenantService appTenantService;

    @Autowired
    private EntPersonnelMapper entPersonnelMapper;

    @Autowired
    private PersonnelService personnelService;

    @Autowired
    private DictionaryAreaService dictionaryAreaService;

    @Resource
    private EntLinkmanMapper entLinkmanMapper;

    @Override
    public String add(EntAddDto req) {
        EntUpdateDto obj = new EntUpdateDto();
        BeanUtils.copyProperties(req, obj);
        return save(obj);
    }

    @Override
    public void saveLinkman(EntLinkmanDto req) {
        EntLinkman obj;
        if (StringUtils.isNullOrEmpty(req.getId())) {
            obj = new EntLinkman();
            obj.setEntId(req.getEntId());
        } else {
            obj = entLinkmanMapper.selectById(req.getId());
        }

        obj.setName(req.getName());
        obj.setPhone(req.getPhone());
        obj.setAddress(req.getAddress());
        obj.setDefaultDeliverTypeDict(req.getDeliverDeliverTypeDict());
        obj.setIsDefault(false);
        obj.insertOrUpdate();
    }

    @Override
    public void update(EntUpdateDto req) {
        save(req);
    }

    @Override
    public void updateLinkman(String entId, String phone, String name, String address) {
        if (StringUtils.isNullOrEmpty(entId) || StringUtils.isNullOrEmpty(phone) || StringUtils.isNullOrEmpty(name)) {
            return;
        }

        LambdaQueryWrapper<EntLinkman> lq = Wrappers.lambdaQuery();
        lq.eq(EntLinkman::getEntId, entId);
        lq.eq(EntLinkman::getPhone, phone);
        Optional<EntLinkman> ret = entLinkmanMapper.selectList(lq).stream().findFirst();
        if (ret.isPresent()) {
            ret.get().setName(name);
            ret.get().setAddress(address);
            ret.get().updateById();
        } else {
            EntLinkman obj = new EntLinkman();
            obj.setEntId(entId);
            obj.setName(name);
            obj.setPhone(phone);
            obj.setAddress(address);
            obj.insert();
        }
    }

    @Override
    public void setDefaultLinkman(String id) {
        EntLinkman obj = entLinkmanMapper.selectById(id);
        if (obj == null) {
            throw new BusinessEntityNotFoundException(id, "联系人");
        }

        for (EntLinkman item : queryLinkman(obj.getEntId())) {
            item.setIsDefault(false);
            item.updateById();
        }
        obj.setIsDefault(true);
        obj.updateById();
    }

    private String save(EntUpdateDto req) {
        Ent obj = getById(req.getId());
        if (obj == null) {
            String id = baseMapper.exist(req.getName());
            if (!StringUtils.isNullOrEmpty(id)) {
                obj = getById(id);
                if (obj == null) {
                    baseMapper.unDelete(id);
                    obj = getById(id);
                }
            } else {
                obj = new Ent();
            }
        }
        obj.setName(req.getName());
        obj.setRemark(req.getRemark());
        obj.setBankAccount(req.getBankAccount());
        obj.setBankName(req.getBankName());
        obj.setTaxNo(req.getTaxNo());
        obj.setTaxRate(req.getTaxRate());
        obj.setTel(req.getTel());
        obj.setCorpAddres(req.getCorpAddres());
        obj.setWxAppId(req.getWxAppId());
        obj.setWxAppSecret(req.getWxAppSecret());
        obj.setWxToken(req.getWxToken());
        obj.setWxMachId(req.getWxMachId());
        obj.setWxMachKey(req.getWxMachKey());
        if (req.getIndustryType() == null) {
            obj.setIndustryType(IndustryTypeEnum.Default.getValue());
        } else {
            obj.setIndustryType(req.getIndustryType().getValue());
        }
        if (req.getProvinceId() != null) {
            obj.setProvinceId(req.getProvinceId());
            obj.setProvinceName(dictionaryAreaService.queryById(req.getProvinceId()));
        }
        if (req.getCityId() != null) {
            obj.setCityId(req.getCityId());
            obj.setCityName(dictionaryAreaService.queryById(req.getCityId()));
        }
        if (req.getCountyId() != null) {
            obj.setCountyId(req.getCountyId());
            obj.setCountyName(dictionaryAreaService.queryById(req.getCountyId()));
        }

        obj.insertOrUpdate();
        return obj.getId();
    }

    @Override
    public void delete(String id) {
        getBaseMapper().deleteById(id);
    }

    @Override
    public void deleteLinkman(String id) {
        entLinkmanMapper.deleteById(id);
    }

    @Override
    public EntLinkman queryLinkmanById(String id) {
        return entLinkmanMapper.selectById(id);
    }

    @Override
    public EntLinkman queryLinkmanByDefault(String entId) {
        LambdaQueryWrapper<EntLinkman> lq = Wrappers.lambdaQuery();
        lq.eq(EntLinkman::getEntId, entId);
        lq.eq(EntLinkman::getIsDefault, true);
        return entLinkmanMapper.selectOne(lq);
    }

    @Override
    public List<EntLinkman> queryLinkman(String entId) {
        LambdaQueryWrapper<EntLinkman> lq = Wrappers.lambdaQuery();
        lq.eq(EntLinkman::getEntId, entId);
        return entLinkmanMapper.selectList(lq);
    }

    @Override
    public List<Ent> queryEntWxConfig() {
        LambdaQueryWrapper<Ent> lq = Wrappers.lambdaQuery();
        lq.isNotNull(Ent::getWxAppId);
        lq.isNotNull(Ent::getWxAppSecret);
        lq.eq(Ent::getIsDelete, false);
        return baseMapper.selectList(lq);
    }

    @Override
    public Ent queryById(String id) {
        return getBaseMapper().selectById(id);
    }


    @Override
    public Ent queryByTenantId(String id) {
        AppTenant tenant = appTenantService.queryById(id);
        if (tenant == null) {
            throw new BusinessException("没有找到指定的租户信息。");
        }
        return baseMapper.selectById(tenant.getEntId());
    }

    @Override
    public Boolean hasInTenant(String tenantId, String userId) {
        return hasInEnt(queryByTenantId(tenantId).getId(), userId);
    }

    @Override
    public Boolean hasInEnt(String entId, String userId) {
        LambdaQueryWrapper<EntPersonnel> lq = Wrappers.lambdaQuery();
        lq.eq(EntPersonnel::getEntId, entId);
        lq.eq(EntPersonnel::getPersonnelId, personnelService.queryByUserId(userId).getId());
        lq.eq(EntPersonnel::getIsDelete, false);
        return entPersonnelMapper.selectOne(lq) != null;
    }

    @Override
    public Boolean hasLinkman(String entId, String phone) {
        LambdaQueryWrapper<EntLinkman> lq = Wrappers.lambdaQuery();
        lq.eq(EntLinkman::getEntId, entId);
        lq.eq(EntLinkman::getPhone, phone);
        return entLinkmanMapper.selectCount(lq) >= 1;
    }
}
